﻿Imports System.Xml
Imports System.IO

Imports ajayumi.develop.VBasic.Core
Imports ajayumi.develop.VBasic.Core.Win
Imports ajDirectory = ajayumi.develop.VBasic.Core.IO.Directory
Imports ajSerializer = ajayumi.develop.VBasic.Core.Xml.Serialization.Serializer
Imports ajayumi.develop.VBasic.Core.Drawing

Public Class FrmSetting

#Region "Variables"
    Private m_XmlPath As String = Application.StartupPath
    Private m_XmlFileName As String = "config.xml"
    Private m_Selection As ImageForm = Nothing
#End Region

#Region "Properties"
    Private m_Trochoid As ITrochoid = Nothing
    Public Property Trochoid() As ITrochoid
        Get
            Return m_Trochoid
        End Get
        Set(ByVal value As ITrochoid)
            m_Trochoid = value
        End Set
    End Property


    Private m_Op As Operate = Operate.None
    Public ReadOnly Property Op() As Operate
        Get
            Return m_Op
        End Get
    End Property

#End Region

#Region "Methods"

    Private Sub BindData()
        If Me.m_Trochoid Is Nothing Then Exit Sub
        Me.ListView1.Items.Clear()
        Dim _Enumerator As IEnumerator(Of ImageForm) = Me.m_Trochoid.GetEnumerator()
        While _Enumerator.MoveNext()
            Dim _ListItem As New ListViewItem(_Enumerator.Current.ProgramInfo.Id)
            _ListItem.Tag = _Enumerator.Current
            _ListItem.SubItems.Add(New ListViewItem.ListViewSubItem(_ListItem, _Enumerator.Current.ProgramInfo.Name))
            _ListItem.SubItems.Add(New ListViewItem.ListViewSubItem(_ListItem, _Enumerator.Current.ProgramInfo.Path))
            _ListItem.SubItems.Add(New ListViewItem.ListViewSubItem(_ListItem, CStr(_Enumerator.Current.ProgramInfo.Order)))
            Me.ListView1.Items.Add(_ListItem)
        End While
    End Sub

    Private Sub BindData(ByVal pgInfo As ImageForm)
        If pgInfo Is Nothing Then Exit Sub
        With pgInfo
            Me.txtpPath.Text = .ProgramInfo.Path
            Me.txtpName.Text = .ProgramInfo.Name
            Me.txtpIcon.Text = String.Empty
            Me.nudOrder.Text = CStr(.ProgramInfo.Order)
            Me.picIcon.Image = .ProgramInfo.FormImage
        End With
    End Sub

    ''' <summary>
    ''' 断开数据绑定，清空
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub ReleaseData()
        Me.txtpName.Text = String.Empty
        Me.txtpPath.Text = String.Empty
        Me.txtpIcon.Text = String.Empty
        Me.nudOrder.Value = 1
        Me.picIcon.Image = Nothing
        Me.m_Selection = Nothing
    End Sub

    ''' <summary>
    ''' 切换控件状态
    ''' </summary>
    ''' <param name="value"></param>
    ''' <remarks></remarks>
    Private Sub SwitchControlsStatus(ByVal value As Boolean)
        Me.txtpName.Enabled = value
        Me.txtpPath.Enabled = value
        Me.txtpIcon.Enabled = value
        Me.nudOrder.Enabled = value
        Me.btnGetAppIcon.Enabled = value
        Me.btnSelpIcon.Enabled = value
        Me.btnSelpPath.Enabled = value
        Me.tsbtnAdd.Enabled = Not value
        Me.tsbtnEdit.Enabled = Not value
        Me.tsbtnDelete.Enabled = Not value
        Me.tsbtnSave.Enabled = value
        Me.tsbtnCancel.Enabled = value
    End Sub

    ''' <summary>
    ''' 保存配置
    ''' </summary>
    ''' <param name="path"></param>
    ''' <remarks></remarks>
    Private Sub Save(ByVal path As String)
        Dim _Enumerator As IEnumerator(Of ImageForm) = Me.m_Trochoid.GetEnumerator()
        Dim _List As New List(Of ProgramInfo)()
        Try
            While _Enumerator.MoveNext()
                _List.Add(_Enumerator.Current.ProgramInfo)
            End While

            For Each _ProgramInfo As ProgramInfo In _List
                _ProgramInfo.FormImage = Nothing
            Next

            Using _MemoryStream As MemoryStream = ajSerializer.SerializeXml(Of List(Of ProgramInfo))(_List)
                Dim _Byte() As Byte = _MemoryStream.ToArray()
                Using _FileStream As New FileStream(path, FileMode.Create, FileAccess.Write)
                    _FileStream.Write(_Byte, 0, _Byte.Length)
                End Using
            End Using
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

#End Region


    Private Sub FrmSetting_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.BindData()

        Me.SwitchControlsStatus(False)
    End Sub

    Private Sub FrmSetting_FormClosed(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles MyBase.FormClosed
        Me.Save(o_ConfigPath)
    End Sub

    Private Sub ListView1_MouseClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles ListView1.MouseClick
        Dim _ListViewItem As ListViewItem = DirectCast(sender, ListView).GetItemAt(e.X, e.Y)
        Me.m_Selection = DirectCast(_ListViewItem.Tag, ImageForm)
        Me.BindData(Me.m_Selection)
    End Sub


    Private Sub ListView1_MouseDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles ListView1.MouseDoubleClick
        Dim _ListViewItem As ListViewItem = DirectCast(sender, ListView).GetItemAt(e.X, e.Y)
        Dim _ImageForm As ImageForm = DirectCast(_ListViewItem.Tag, ImageForm)
        Try
            ajDirectory.OpenFolder(_ImageForm.ProgramInfo.Path, True)
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Exclamation)
        End Try
    End Sub

    Private Sub btnSelpPath_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSelpPath.Click
        Dim _OpenFileDialog As New OpenFileDialog()
        _OpenFileDialog.Filter = "所有文件|*.*"
        If _OpenFileDialog.ShowDialog() = Windows.Forms.DialogResult.OK Then
            Me.DoWork(_OpenFileDialog.FileName)
        End If
    End Sub

    Private Sub btnSelpIcon_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSelpIcon.Click
        Dim _OpenFileDialog As New OpenFileDialog()
        _OpenFileDialog.Filter = "图片|*.png;*.gif"
        If _OpenFileDialog.ShowDialog() = Windows.Forms.DialogResult.OK Then
            Me.txtpIcon.Text = _OpenFileDialog.FileName
            Me.picIcon.Image = Image.FromFile(_OpenFileDialog.FileName)
        End If
    End Sub

    Private Sub txtpPath_DragEnter(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles txtpPath.DragEnter
        If e.Data.GetDataPresent(DataFormats.FileDrop) Then
            e.Effect = DragDropEffects.Link
        Else
            e.Effect = DragDropEffects.None
        End If
    End Sub

    Private Sub txtpPath_DragDrop(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles txtpPath.DragDrop
        Dim _Path As String = CType(e.Data.GetData(DataFormats.FileDrop), String())(0).ToString()
        Me.DoWork(_Path)
    End Sub

    Private Sub txtpIcon_DragEnter(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles txtpIcon.DragEnter
        If e.Data.GetDataPresent(DataFormats.FileDrop) Then
            e.Effect = DragDropEffects.Link
        Else
            e.Effect = DragDropEffects.None
        End If
    End Sub

    Private Sub txtpIcon_DragDrop(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles txtpIcon.DragDrop
        Dim _Path As String = CType(e.Data.GetData(DataFormats.FileDrop), String())(0).ToString()
        If ImageHelper.IsImageFile(_Path) Then
            Me.txtpIcon.Text = _Path
            Me.picIcon.Image = Image.FromFile(_Path)
        End If
    End Sub

    Private Sub btnGetAppIcon_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGetAppIcon.Click
        Me.picIcon.Image = Me.GetAppIcon(Me.txtpPath.Text.Trim())
    End Sub

    ''' <summary>
    ''' 选择程序后的自动工作
    ''' </summary>
    ''' <param name="filePath">文件路径</param>
    Sub DoWork(ByVal filePath As String)
        Me.txtpPath.Text = filePath
        Me.txtpName.Text = System.IO.Path.GetFileNameWithoutExtension(filePath)

        Me.picIcon.Image = Me.GetAppIcon(filePath)
    End Sub

    ''' <summary>
    ''' 获取应用程序图标
    ''' </summary>
    ''' <param name="appPath">应用程序路径</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Function GetAppIcon(ByVal appPath As String) As Image
        Dim _Bitmap As Bitmap = New Bitmap(32, 32)

        Try
            _Bitmap = Icon.ExtractAssociatedIcon(appPath).ToBitmap()
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Exclamation)
        Finally
        End Try

        Return _Bitmap
    End Function

    Private Sub tsbtnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsbtnAdd.Click
        Me.ReleaseData()
        Me.nudOrder.Value = Me.ListView1.Items.Count + 1
        Me.SwitchControlsStatus(True)
        Me.m_Op = Operate.Add
    End Sub

    Private Sub tsbtnEdit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsbtnEdit.Click
        Me.SwitchControlsStatus(True)
        Me.m_Op = Operate.Edit
    End Sub

    Private Sub tsbtnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsbtnDelete.Click
        If Me.m_Selection Is Nothing Then Exit Sub

        If MessageBox.Show("是否删除所选项？", "询问", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
            Try
                Me.m_Trochoid.Remove(Me.m_Selection)

                Me.BindData()
            Catch ex As Exception
                MsgBox(ex.Message)
            End Try
        End If

    End Sub

    Private Sub tsbtnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsbtnSave.Click
        Try
            Dim _ProgramInfo As ProgramInfo = Nothing
            Dim _FormImageData As String = String.Empty
            Dim _IconPath As String = Me.txtpIcon.Text.Trim()

            If String.IsNullOrEmpty(_IconPath) = False Then
                _FormImageData = ImageHelper.ImageToBase64String(_IconPath, Imaging.ImageFormat.Png)
            Else
                If Me.picIcon.Image IsNot Nothing Then
                    _FormImageData = ImageHelper.ImageToBase64String(Me.picIcon.Image, Imaging.ImageFormat.Png)
                Else
                    _FormImageData = ImageHelper.ImageToBase64String(My.Resources.none, Imaging.ImageFormat.Png)
                End If
            End If

            Select Case Me.Op
                Case Operate.Add
                    _ProgramInfo = New ProgramInfo()
                    With _ProgramInfo
                        .Id = System.Guid.NewGuid.ToString()
                        .Name = Me.txtpName.Text.Trim()
                        .Path = Me.txtpPath.Text.Trim()
                        .Order = CInt(Me.nudOrder.Value)
                        .FormImageData = _FormImageData
                        .FormImageSize = Me.m_Trochoid.ItemSize
                        .FormImage = ImageHelper.Base64StringToImage(_FormImageData)
                    End With
                    Dim _ImageForm As New ImageForm(_ProgramInfo)
                    Me.m_Trochoid.Add(_ImageForm)
                    Exit Select
                Case Operate.Edit
                    _ProgramInfo = Me.m_Trochoid.Find(Me.m_Selection).ProgramInfo
                    With _ProgramInfo
                        .Name = Me.txtpName.Text.Trim()
                        .Path = Me.txtpPath.Text.Trim()
                        .Order = CInt(Me.nudOrder.Value)
                        If String.IsNullOrEmpty(_IconPath) = False OrElse Me.picIcon.Image IsNot Nothing Then
                            .FormImageData = _FormImageData
                            .FormImageSize = Me.m_Trochoid.ItemSize
                            .FormImage = ImageHelper.Base64StringToImage(_FormImageData)
                        End If
                    End With
                    Exit Select
            End Select

            Me.SwitchControlsStatus(False)
            Me.m_Op = Operate.None
            Me.BindData()
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Private Sub tsbtnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsbtnCancel.Click
        Me.SwitchControlsStatus(False)
        Me.BindData(Me.m_Selection)
        Me.m_Op = Operate.None
    End Sub




End Class
